package com.shoulder.authorizationserver.exception;

import com.shoulder.core.api.ApiResult;
import com.shoulder.core.exception.BizExceptionHandler;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Slf4j
public class AuthorizationExceptionHandler extends BizExceptionHandler {
    @Override
    public ApiResult<Object> handleException(Exception ex) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        if (ex instanceof AccessDeniedException) {
            log.error("访问被拒绝:{},url = {}", ex.getMessage(), request.getRequestURI(), ex);
            return ApiResult.badRequest(null, "无权访问");
        }
        if (ex instanceof BadCredentialsException) {
            log.error("访问被拒绝:{},url = {}", ex.getMessage(), request.getRequestURI(), ex);
            return ApiResult.badRequest(null, "用户名或密码不存在");
        }
        if (ex instanceof OAuth2AuthenticationException) {
            log.error("oauth2认证失败:{},url = {}", ex.getMessage(), request.getRequestURI(), ex);
            return ApiResult.badRequest(null, ex.getMessage());
        }
        return super.handleException(ex);
    }
}
